package com.caowei.weicimpress.weicimpress;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.caowei.weicimpress.weicimpress.widget.AlertDialog;
import com.caowei.weicimpress.weicimpress.widget.Toast;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnItemClick;
import butterknife.OnItemLongClick;

/**
 * Created by caoweiPc on 2014/8/9.
 */
public class SearchFragment  extends BaseFragment implements View.OnClickListener,
        AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener{
    private static final int REQUESTCODE0=0;
    private File rootFile;
    private String searchStr;
    private List<FileInfoBean> mData;
    private String currentPath;
    private ActionBarBaseFragment selectedFrgament;
    @InjectView(R.id.list)
    ListView listView;
    @InjectView(R.id.head)
    LinearLayout headView;
    @InjectView(R.id.searchtime)
    TextView searchtime;
    @InjectView(R.id.searchsrc)
    TextView searchsrc;
    @InjectView(R.id.refresh)
    ImageView refresh;
    @InjectView(R.id.progress)
    LinearLayout progress;
    @InjectView(R.id.tip)
    TextView tip;
    @InjectView(R.id.innerprocess)
    ImageView innerprocess;
    private SearchAdapter searchadapter;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.searchfragment_layout,
                container,false);
        ButterKnife.inject(this, v);
        if(Build.VERSION_CODES.HONEYCOMB>=Build.VERSION.SDK_INT){
            Bitmap bitmap= BitmapFactory.decodeResource(getActivity().getResources(),
                    R.drawable.cover_bg);
            progress.setBackgroundColor(bitmap.getPixel(bitmap.getWidth()/2,bitmap.getHeight()/2));
        }
        return v;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        searchadapter=new SearchAdapter();
        searchadapter.setmContext(getActivity());
        searchadapter.setmData(new ArrayList<FileInfoBean>());
        listView.setAdapter(searchadapter);
    }

    public String getSearchStr() {
        return searchStr;
    }

    public void setSearchStr(String searchStr) {
        this.searchStr = searchStr;
    }


    public String getCurrentPath() {
        return currentPath;
    }

    public void setCurrentPath(String currentPath) {
        this.currentPath = currentPath;
    }



    public ActionBarBaseFragment getSelectedFrgament() {
        return selectedFrgament;
    }

    public void setSelectedFrgament(ActionBarBaseFragment selectedFrgament) {
        this.selectedFrgament = selectedFrgament;
    }
    public List<FileInfoBean> getmData() {
        return mData;
    }

    public void setmData(List<FileInfoBean> mData) {
        this.mData = mData;
    }




    public File getRootFile() {
        return rootFile;
    }

    public void setRootFile(File rootFile) {
        this.rootFile = rootFile;
    }

    @Override
    public void refresh() {
        if(selectedFrgament!=null) {
            AsyncTask<Object, Object, List<FileInfoBean>> asyncTask = new AsyncTask<Object, Object,
                    List<FileInfoBean>>() {
                @Override
                protected List<FileInfoBean> doInBackground(Object[] params) {
                    List<FileInfoBean> datas = new ArrayList<FileInfoBean>();
                    mData = selectedFrgament.getDataResult();
                    if (!TextUtils.isEmpty(searchStr)) {
                        for (FileInfoBean bean : mData) {
                            if (bean.getFileName().contains(searchStr)) {
                                datas.add(bean);
                            }
                        }
                    }
                    return datas;
                }

                @Override
                protected void onPostExecute(List<FileInfoBean> beans) {
                    searchadapter.setmData(beans);
                    searchadapter.notifyDataSetChanged();
                    String str1 = getActivity().getResources().getString(R.string.searchtime,
                            Utils.formateDate(Calendar.getInstance()));
                    searchtime.setText(str1);
                    StringBuilder sb1 = new StringBuilder(rootFile.getName());
                    sb1.append(":").append(currentPath);
                    String str2 = getActivity().getResources().getString(R.string.searchpath,
                            sb1.toString());
                    searchsrc.setText(str2);
                    showCoverProgress(false,null);
                    if(refresh.getVisibility()==View.GONE){
                        refresh.setVisibility(View.VISIBLE);
                    }

                }
            };

           /* StringBuilder sb = new StringBuilder(getActivity().getResources().getString(R.string.searchfiletask)).
                    append(searchStr).append(
                    getActivity().getResources().getString(R.string.fatherdir1)
            );*/
            showCoverProgress(true,"搜索中...");
            asyncTask.execute();
        }
    }


    private void showCoverProgress(boolean show,String msg){
        tip.setText(msg);
        if(show){
            progress.setVisibility(View.VISIBLE);
            AnimationDrawable mAnimationDrawable = (AnimationDrawable) innerprocess.getBackground();
            mAnimationDrawable.start();
        }else{
            progress.setVisibility(View.GONE);
            AnimationDrawable mAnimationDrawable = (AnimationDrawable) innerprocess.getBackground();
            mAnimationDrawable.stop();
        }
    }

    @OnClick(R.id.refresh)
    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.refresh:
                refresh();
                break;
        }
    }

    @OnItemClick(R.id.list)
    @Override
    public void onItemClick(final AdapterView<?> parent, View view, int position, long id) {
        FileInfoBean bean= (FileInfoBean) parent.getAdapter().getItem(position);
        if(bean.isDir()){
            File rootFile1=bean.getRootFile();
            StringBuilder sb=new StringBuilder(bean.getParentPath());
            sb.append(File.separator).append(bean.getFileName());
            String path=Utils.normalizePath(sb.toString());
            Activity activity=getActivity();
            if(activity instanceof OnSwitchFragment) {
                if(rootFile1.exists()&&rootFile1.isDirectory()){
                    final String path1=String.valueOf(path);
                    OnSwitchFragment switchFragment= (OnSwitchFragment) activity;
                    switchFragment.switchFragment(SysFileFragment.class,new Callback() {
                        @Override
                        public void onCallback(Callback1 callback) {
                            selectedFrgament.refreshFromPath(path1,false);
                        }
                    });
                }else if(rootFile1.exists()&&rootFile1.isFile()){
                    path=Utils.dropHeadStr(path,File.separator);
                    final String path1=String.valueOf(path);
                    OnSwitchFragment switchFragment= (OnSwitchFragment) activity;
                    switchFragment.switchFragment(CompressFileFragment.class,new Callback() {
                        @Override
                        public void onCallback(Callback1 callback) {
                            selectedFrgament.refreshFromPath(path1,false);
                        }
                    });
                }
            }
        }else{
            Activity activity=getActivity();
            File rootFile1=bean.getRootFile();
            if(activity instanceof OnSwitchFragment) {
                if(rootFile1.exists()&&rootFile1.isDirectory()&&bean.isCompressed()){
                    OnSwitchFragment switchFragment= (OnSwitchFragment) activity;
                    StringBuilder sb=new StringBuilder(bean.getParentPath());
                    sb.append(File.separator).append(bean.getFileName());
                    final File compressedFile=new File(Utils.dropTailStr(Utils.normalizePath(sb.toString()),
                            File.separator));
                    switchFragment.switchFragment(CompressFileFragment.class,new Callback() {
                        @Override
                        public void onCallback(Callback1 callback) {
                            callback.onCallback(SearchFragment.class,compressedFile);
                        }
                    });
                    return;
                }
            }
            //todo  temprary
            Toast.makeText(getActivity(),"不可打开文件",Toast.LENGTH_SHORT).show();
        }
    }
    @OnItemLongClick(R.id.list)
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        final FileInfoBean bean= (FileInfoBean) parent.getAdapter().getItem(position);

        List<GenerateDialog.ActionItem> opers1=new ArrayList<GenerateDialog.ActionItem>();
        String arr1[]=  getActivity().getResources().
                getStringArray(R.array.sysfilefragment_longitemclick);
        for(int i=0;i<arr1.length;i++){
            String str=arr1[i];
            GenerateDialog.ActionItem actionItem=new GenerateDialog.ActionItem();
            actionItem.setName(str);
            final int j=i;
            actionItem.setCallback(new GenerateDialog.Callback() {
                @Override
                public void callback(Object[] t) {
                    exeOper1(j, bean);
                }
            });
            opers1.add(actionItem);
        }

        List<GenerateDialog.ActionItem> opers2=new ArrayList<GenerateDialog.ActionItem>();
        String arr2[]=  getActivity().getResources().
                getStringArray(R.array.compressfragment_longitemclick);
        for(int i=0;i<arr2.length;i++){
            String str=arr2[i];
            GenerateDialog.ActionItem actionItem=new GenerateDialog.ActionItem();
            actionItem.setName(str);

            final int j=i;
            actionItem.setCallback(new GenerateDialog.Callback() {
                @Override
                public void callback(Object[] t) {
                    exeOper2(j,bean);
                }
            });
            opers2.add(actionItem);
        }

        List<GenerateDialog.ActionItem> opers=null;
        File rootFile1=bean.getRootFile();
        if(rootFile1.exists()&&rootFile1.isDirectory()){
            opers=opers1;
        }else if(rootFile1.exists()&&rootFile1.isFile()){
            opers=opers2;
        }
        AlertDialog selectOperDialog= GenerateDialog.createSelectOperDialog(
                getActivity().getResources().getString(R.string.selectoper),
                getActivity(), opers);
        selectOperDialog.show();
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==Activity.RESULT_OK){
            switch (requestCode){
                case REQUESTCODE0:
                    selectedFrgament.onActivityResult(SysFileFragment.REQUESTCODE,
                            Activity.RESULT_OK,data);
                    ((ActionBarActivity)getActivity()).getSupportActionBar().setSelectedNavigationItem(
                            Utils.SYSFRAG_TAB_INDEX
                    );
                    break;
            }
        }
    }

    private void exeOper1(int position,  final FileInfoBean bean){
        switch (position){
            case 0:
                info(bean);
                break;
            case 1:
                compress(bean);
                break;
            case 2:
                extract(bean);
                break;
            case 3:
                GenerateDialog.createVerifyDialog(getActivity(),
                        getActivity().getResources().getString(R.string.verify_title),
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                delete(bean);
                            }
                        }, null
                );
                break;
        }
    }

    private void exeOper2(int position, final FileInfoBean bean){
        switch (position){
            case 0:
                info(bean);
                break;
            case 1:
                extract(bean);
                break;
            case 2:
                GenerateDialog.createVerifyDialog(getActivity(),
                        getActivity().getResources().getString(R.string.verify_title),
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                delete(bean);
                            }
                        },null);
                break;
        }
    }

    private void extract(FileInfoBean bean){
        if(bean.isCompressed()){
            Activity activity= getActivity();
            ((ActionBarActivity)getActivity()).getSupportActionBar().setSelectedNavigationItem(
                    Utils.SYSFRAG_TAB_INDEX
            );
            if(activity instanceof GetFragment){
                if(selectedFrgament instanceof SysFileFragment){
                    SysFileFragment fileFragment= (SysFileFragment) selectedFrgament;
                    fileFragment.extract(bean);
                }else if(selectedFrgament instanceof CompressFileFragment){
                    CompressFileFragment fragment= (CompressFileFragment) selectedFrgament;
                    fragment.extractEle(bean);
                }
            }
        }else{
            StringBuilder sb=new StringBuilder(bean.getFileName());
            sb.append(":").append(getActivity().getResources().getString(R.string.isnotcompressfile));
            Toast.makeText(getActivity(),sb.toString(),Toast.LENGTH_SHORT).show();
        }
    }

    private void compress(FileInfoBean bean){
        Intent i=new Intent(getActivity(),OperationCompressActivity.class);
        i.putExtra("bean",bean);
        startActivityForResult(i, REQUESTCODE0);
    }

    private void info(FileInfoBean bean){
        String[] arr=null;
        String title;
        String[][] fileProperties=null;
        File rootFile1=bean.getRootFile();
        if(bean.isDir()){
            title=getActivity().getResources().getString(R.string.dirpropertyname);
            if(rootFile1.exists()&&rootFile1.isDirectory()){
                arr=getActivity().getResources().getStringArray(R.array.dirproperty);
                StringBuilder sb=new StringBuilder(bean.getParentPath());
                sb.append(File.separator).append(bean.getFileName());
                String filePath= Utils.drop2Str(Utils.normalizePath(sb.toString()), File.separator);
                File file=new File(filePath);
                fileProperties=new String[][]{
                        new String[]{bean.getFileName()},
                        new String[]{Utils.formateDate(file.lastModified(),Utils.DEFAULTDATEPATTERNWITHA)},
                        new String[]{String.valueOf(bean.getNumOfSubFile())},
                        new String[]{String.valueOf(file.canRead())},
                        new String[]{String.valueOf(file.canWrite())},
                        new String[]{Utils.normalSizeStr(Utils.getInternalFreeAllSpace()),
                                Utils.normalSizeStr(Utils.getExternalFreeAllSpace())},
                        new String[]{Utils.normalSizeStr(Utils.getInternalAllSpace()),
                                Utils.normalSizeStr(Utils.getExternalAllSpace())}
                };
            }else if(rootFile1.exists()&&rootFile1.isFile()){
                arr=getActivity().getResources().getStringArray(R.array.compressdirproperty);
                long itemLastModifyTime=bean.getLastModFileTime();
                long rootFile1LastModityTime=rootFile1.lastModified();
                itemLastModifyTime=itemLastModifyTime<rootFile1LastModityTime?rootFile1LastModityTime:
                        itemLastModifyTime;
                fileProperties=new String[][]{
                        new String[]{bean.getFileName()},
                        new String[]{Utils.formateDate(itemLastModifyTime,Utils.DEFAULTDATEPATTERNWITHA)},
                        new String[]{String.valueOf(bean.getNumOfSubFile())},
                        new String[]{Utils.normalSizeStr(
                                BigDecimal.valueOf(bean.getRootFile().length()))}
                };
            }
        }else{
            title=getActivity().getResources().getString(R.string.filepropertyname);
            if(rootFile1.exists()&&rootFile1.isDirectory()){
                arr=getActivity().getResources().getStringArray(R.array.fileproperty);
                StringBuilder sb=new StringBuilder(bean.getParentPath());
                sb.append(File.separator).append(bean.getFileName());
                String filePath= Utils.drop2Str(Utils.normalizePath(sb.toString()), File.separator);
                File file=new File(filePath);
                fileProperties=new String[][]{
                        new String[]{bean.getFileName()},
                        new String[]{Utils.formateDate(file.lastModified(),Utils.DEFAULTDATEPATTERNWITHA)},
                        new String[]{ Utils.normalSizeStr(bean.getSize()) },
                        new String[]{String.valueOf(file.canRead())},
                        new String[]{String.valueOf(file.canWrite())},
                        new String[]{Utils.normalSizeStr(Utils.getInternalFreeAllSpace()),
                                Utils.normalSizeStr(Utils.getExternalFreeAllSpace())},
                        new String[]{Utils.normalSizeStr(Utils.getInternalAllSpace()),
                                Utils.normalSizeStr(Utils.getExternalAllSpace())}
                };
            }else if(rootFile1.exists()&&rootFile1.isFile()){
                arr=getActivity().getResources().getStringArray(R.array.compressfileproperty);
                long itemLastModifyTime=bean.getLastModFileTime();
                long rootFile1LastModityTime=rootFile1.lastModified();
                itemLastModifyTime=itemLastModifyTime<rootFile1LastModityTime?rootFile1LastModityTime:
                        itemLastModifyTime;
                fileProperties=new String[][]{
                        new String[]{bean.getFileName()},
                        new String[]{Utils.formateDate(itemLastModifyTime,Utils.DEFAULTDATEPATTERNWITHA)},
                        new String[]{Utils.normalSizeStr(bean.getSize())},
                        new String[]{Utils.normalSizeStr(
                                BigDecimal.valueOf(bean.getRootFile().length()))}
                };
            }
        }
        List<GenerateDialog.ActionItem> list=new ArrayList<GenerateDialog.ActionItem>();
        String[][] fileProperties1=fileProperties;
        for(int i=0;i<arr.length;i++){
            String str=arr[i];
            GenerateDialog.ActionItem actionItem=new GenerateDialog.ActionItem();
            actionItem.setName(String.format(str,(Object[])fileProperties1[i]));
            list.add(actionItem);
        }
        AlertDialog dialog= GenerateDialog.createSelectOperDialog(title,getActivity(),list);
        dialog.show();
    }

    private void delete(final FileInfoBean bean){
        StringBuilder sb=new StringBuilder();
        sb.append(bean.getParentPath()).append(File.separator).append(bean.getFileName());
        String path=Utils.normalizePath(sb.toString());
        path=Utils.dropHeadStr(path,File.separator);
        if(!bean.isDir()){
            path=Utils.dropTailStr(path,File.separator);
        }
        final String path1=String.valueOf(path);
        AsyncTask task= new AsyncTask<Object,Object,Boolean>(){
            @Override
            protected Boolean doInBackground(Object... params) {
                return Utils.del(path1);
            }
            @Override
            protected void onPostExecute(Boolean b) {
                if(b){
                    String parentPath=bean.getParentPath();
                    parentPath=Utils.dropHeadStr(Utils.normalizePath(parentPath),
                            File.separator);
                    selectedFrgament.refreshFromPath(parentPath);
                    SearchAdapter adapter= (SearchAdapter) listView.getAdapter();
                    List<FileInfoBean> beans=adapter.getmData();
                    beans.remove(bean);
                    adapter.setmData(beans);
                    adapter.notifyDataSetChanged();
                }
            }
        };
        task.execute();
    }

    private static class SearchAdapter extends BaseAdapter{
        private List<FileInfoBean> mData;
        private Context mContext;

        public List<FileInfoBean> getmData() {
            return mData;
        }

        public void setmData(List<FileInfoBean> mData) {
            this.mData = mData;
        }

        public Context getmContext() {
            return mContext;
        }

        public void setmContext(Context mContext) {
            this.mContext = mContext;
        }


        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public FileInfoBean getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return( (Object)mData.get(position)).hashCode();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder=null;
            if(convertView==null){
                convertView= LayoutInflater.from(mContext).
                        inflate(R.layout.searchfragment_layout_item, parent, false);
                viewHolder=new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            }else{
                viewHolder= (ViewHolder) convertView.getTag();
            }
            viewHolder.img.setImageResource(mData.get(position).getIcoId());
            viewHolder.fileName.setText(mData.get(position).getFileName());
            viewHolder.time_authrity.setText(mData.get(position).getDate_authrity());
            return convertView;
        }
    };


    static class ViewHolder{
        @InjectView(R.id.img)
        ImageView img;
        @InjectView(R.id.fileName)
        TextView fileName;
        @InjectView(R.id.time_authrity)
        TextView time_authrity;
        public ViewHolder(View v){
            ButterKnife.inject(this,v);
        }
    }
}
